package com.alibaba.dingtalk.openapi.rest;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dingtalk.openapi.demo.OApiException;
import com.alibaba.dingtalk.openapi.demo.auth.AuthHelper;
import com.alibaba.dingtalk.openapi.demo.utils.aes.DingTalkJsApiSingnature;
import com.alibaba.dingtalk.openapi.demo.utils.aes.Utils;

@RestController
@RequestMapping("/jsApi")
public class JsApiController {
	
	 //2. 声明一个Logger，这个是static的方式，我比较习惯这么写。
	  private final static Logger logger = LoggerFactory.getLogger(JsApiController.class);
	  
	/**
	 * 【计算当前请求的jsapi的签名数据】 ----------------------------------------
	 * springboot获取URL请求参数-通过HttpServletRequest接收
	 * 
	 * @param request
	 * @return
	 */
	// @RequestMapping(value = "/getConfig", method = RequestMethod.GET)	
	@RequestMapping("/getConfig")
	@ResponseBody
	public String getConfigTwo(@RequestParam(value = "url", required = false) String url,@RequestParam(value = "corpId", required = false) String corpId)throws OApiException {
		return AuthHelper.getConfig(url);
	}

	
	/**
	 * 方法一：【计算当前请求的jsapi的签名数据】
	 * @param  url  参数URL 必须时，在钉钉控制台中设置的-设置的首页地址（否则认证将失效）
	 * @param  corpId
	 * @return Map
	 * @throws OApiException
	 */
	@RequestMapping("/get_js_config")
	@ResponseBody
	public Map getJsConfig(@RequestParam(value = "url", required = false) String url,@RequestParam(value = "corpId", required = false) String corpId) throws OApiException {
	
		//获取access_token，
		String accessToken = AuthHelper.getAccessToken();
		
		//获取JSTicket, 用于js的签名计算
		String JSTicket = AuthHelper.getJsapiTicket(accessToken);

		String nonceStr = Utils.getRandomStr(8);
		
		Long timeStamp = System.currentTimeMillis();
		try {
			// 获取jsapi签名
			String signature = DingTalkJsApiSingnature.getJsApiSingnature(url, nonceStr, timeStamp, JSTicket);
			Map JsApiConfig = new HashMap();
			JsApiConfig.put("signature", signature);
			JsApiConfig.put("nonceStr", nonceStr);
			JsApiConfig.put("timeStamp", timeStamp);
			JsApiConfig.put("corpId", corpId);
			return JsApiConfig;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(" message ", e.getMessage());
		}
		return null;
	}
}